/**
 * Created by yunpeng on 2014/12/22.
 */
var express = require('express');
var router = express.Router();
var fs = require('fs');
var gm = require('gm');//处理图片

var debug = require('debug')('circle');

var Page = require("../models/Page");
var circle = require('../models/CirCle');
var CarClub = circle.CarClub,
    SelfDriving = circle.SelfDriving,
    Voice = circle.Voice,
    Activity = circle.Activity;


var act = require('../models/CarActivity');
var UserModel = require('../models/users').Users;

router.post('/carClub/carClubList',function(req,res){
    var params = [req.body.ccDate1,req.body.ccDate2,req.body.ccName];//查询条件

    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new CarClub().getCarClubList(params,page,function(result){
        res.send(result);
        debug(result);
    });
    debug('车友汇信息列表');
});

/**
 * 添加车友汇信息
 */
router.post('/auth/carClub/addCarClub', function(req,res){

    var coords = req.body.coords;
    var imgPathOfBus = 'images/circleimgs/carclub/cc'+req.body.cid;//根据城市ID创建目录
    console.log(req.body.coords+' '+imgPathOfBus);
    if(!fs.existsSync('public/'+imgPathOfBus)){
        fs.mkdirSync('public/'+imgPathOfBus);
    }
    console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
    gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
        .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
            if (!err){
                fs.unlinkSync(req.files.file.path);//删除文件原
                var img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                new CarClub(req.body.name,req.body.title,req.body.contacts,req.body.tel,req.body.phone,req.body.address,req.body.content,img,req.body.cid,new Date())
                    .save(function(result){
                        res.setHeader('Content-Type','text/html');
                        res.send(result);
                    });
            }
        });
});

/**
 * 编辑车友汇信息
 */
router.post('/auth/carClub/editCarClub', function(req,res){
    console.log(req.body.coords);
    var img='public/'+req.body.pic;
    if(req.files.file){//判断图片需不需要更新
        var coords = req.body.coords;
        var imgPathOfBus = 'images/circleimgs/carclub/cc'+req.body.cid;//根据产品ID创建目录
        if(!fs.existsSync('public/'+imgPathOfBus)){
            fs.mkdirSync('public/'+imgPathOfBus);
        }
        console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
        gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
            .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
                if (!err){
                    fs.unlinkSync(req.files.file.path);//删除文件原
                    fs.unlinkSync(img);//删除原来的图片
                    img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                    carClubUodate(req, res, img);
                }
            });
    }else{
        carClubUodate(req, res, req.body.pic);
    }
});

/**
 * 删除选中
 */
router.post('/auth/carClub/delCarClub', function(req,res){
    var ids = req.body['ids'];
    console.log(ids);
    var imgs = req.body['imgs'];
    new CarClub().delCarClubs(ids,function(result){
        imgs = imgs.split(',');
        for(var i=0;i<imgs.length;i++){
            fs.unlinkSync('public/'+imgs[i]);//删除原来的图片
        }
        res.send(result);
    });
});

/**
 * 更新信息
 * @param req
 * @param res
 * @param img
 */
function carClubUodate(req, res, img){
    var carClub = new CarClub(req.body.name,req.body.title,req.body.contacts,req.body.tel,req.body.phone,req.body.address,req.body.content,
        img,Number(req.body.cid),new Date(req.body.createtime));
    carClub.id = req.body.id;
    carClub.update(function(result){
        res.setHeader('Content-Type','text/html');
        res.send(result);
    });
}

/**
 * 自驾游活动列表
 */
router.post('/sd/sdList',function(req,res){
    var params = [req.body.ccDate1,req.body.ccDate2,req.body.ccName,req.body.city];//查询条件

    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new SelfDriving().getSdList(params,page,function(result){
        res.send(result);
    });
    debug('车友汇信息列表');
});


/**
 * 添加自驾游信息
 */
router.post('/auth/sd/addSd', function(req,res){

    var coords = req.body.coords;
    var imgPathOfBus = 'images/circleimgs/sd/sd'+req.body.cid;//根据城市ID创建目录
    console.log(req.body.coords+' '+imgPathOfBus);
    if(!fs.existsSync('public/'+imgPathOfBus)){
        fs.mkdirSync('public/'+imgPathOfBus);
    }
    console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
    gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
        .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
            if (!err){
                fs.unlinkSync(req.files.file.path);//删除文件原
                var img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                new SelfDriving(req.body.title,req.body.content,req.body.price,new Date(req.body.starttime),
                    new Date(req.body.endtime),0,img,req.body.cid,new Date())
                    .save(function(result){
                        res.setHeader('Content-Type','text/html');
                        res.send(result);
                    });
            }
        });
});

/**
 * 编辑自驾游信息
 */
router.post('/auth/sd/editSd', function(req,res){
    console.log(req.body.coords);
    var img='public/'+req.body.pic;
    if(req.files.file){//判断图片需不需要更新
        var coords = req.body.coords;
        var imgPathOfBus = 'images/circleimgs/sd/sd'+req.body.cid;//根据产品ID创建目录
        if(!fs.existsSync('public/'+imgPathOfBus)){
            fs.mkdirSync('public/'+imgPathOfBus);
        }
        console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
        gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
            .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
                if (!err){
                    fs.unlinkSync(req.files.file.path);//删除文件原
                    fs.unlinkSync(img);//删除原来的图片
                    img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                    sdUodate(req, res, img);
                }
            });
    }else{
        sdUodate(req, res, req.body.pic);
    }
});

/**
 * 删除选中
 */
router.post('/auth/sd/delSd', function(req,res){
    var ids = req.body['ids'];
    console.log(ids);
    var imgs = req.body['imgs'];
    new SelfDriving().delSd(ids,function(result){

        res.send(result);
    });
});

/*查看报名订单*/
router.post('/auth/sd/getorders', function(req, res){
    var option = {
        did:req.body.did,
        rows:req.body.rows,
        page:req.body.page
    };
    new SelfDriving().getOrders(option, function(data){
        sendResult(res,data);
    })
})

/**
 * 更新信息
 * @param req
 * @param res
 * @param img
 */
function sdUodate(req, res, img){
    var selfDriving = new SelfDriving(req.body.title,req.body.content,req.body.price,new Date(req.body.starttime),
        new Date(req.body.endtime),req.body.count,img,req.body.cid,new Date(req.body.createtime));
    selfDriving.id = req.body.id;
    selfDriving.update(function(result){
        res.setHeader('Content-Type','text/html');
        res.send(result);
    });
}

/* 车友活动 */
router.post('/activity/list', function(req, res){
   var option = {
       fromDate:req.body.beginTime,
       toDate:req.body.endTime,
       searchName:req.body.searchName,
       page:req.body.page,
       rows:req.body.rows,
       sort:req.body.sort,
       order:req.body.order,
       city:req.body.city
   };
    act.list(option, function(resultSet){
        res.setHeader('Content-Type','text/html');
        res.send(resultSet);
    })
});

router.post('/auth/activity/add', function(req, res){
    var activity = {
        title:req.body.title,
        content:req.body.content,
        total:Number(req.body.total),
        currenttotal:0,
        starttime:req.body.starttime,
        endtime:req.body.endtime,
        cid:Number(req.body.cid),
        createuserid:1
    };

    var coords = req.body.coords;
    var imgPathOfBus = 'images/circleimgs/sd/sd'+req.body.cid;//根据城市ID创建目录
    console.log(req.body.coords+' '+imgPathOfBus);
    if(!fs.existsSync('public/'+imgPathOfBus)){
        fs.mkdirSync('public/'+imgPathOfBus);
    }
    console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
    gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
        .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
            if (!err){
                fs.unlinkSync(req.files.file.path);//删除文件原
                var img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                activity.pic = img;
                act.saveUpdate(activity, function(result){
                    res.setHeader('Content-Type','text/html');
                    res.send(resultSet);
                })
            }
        });
})

router.post('/auth/activity/edit', function(req, res){
    var activity = {
        id:req.body.id,
        title:req.body.title,
        content:req.body.content,
        total:Number(req.body.total),
        currenttotal:Number(req.body.currenttotal),
        starttime:req.body.starttime,
        endtime:req.body.endtime,
        cid:Number(req.body.cid)
    };

    var img='public/'+req.body.pic;
    if(req.files.file){//判断图片需不需要更新
        var coords = req.body.coords;
        var imgPathOfBus = 'images/circleimgs/sd/sd'+req.body.cid;//根据产品ID创建目录
        if(!fs.existsSync('public/'+imgPathOfBus)){
            fs.mkdirSync('public/'+imgPathOfBus);
        }
        console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
        gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
            .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
                if (!err){
                    fs.unlinkSync(req.files.file.path);//删除文件原
                    fs.unlinkSync(img);//删除原来的图片
                    img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                    activity.pic = img;
                    act.saveUpdate(activity, function(result){
                        res.setHeader('Content-Type','text/html');
                        res.send(resultSet);
                    })
                }
            });
    }
})

router.post('/auth/activity/del', function(req,res){
    var ids = req.body['ids'];
    console.log(ids);
    act.delete(ids, function(result){
        res.setHeader('Content-Type','text/html');
        res.send(result);
    })
});

router.post('/auth/activity/getorders', function(req, res){
    var option = {
        aid:req.body.aid,
        rows:req.body.rows,
        page:req.body.page
    };
    new Activity().getOrders(option, function(data){
        sendResult(res,data);
    })
})

/**
 * 我代言活动列表
 */
router.post('/voice/voiceList',function(req,res){
    var params = [req.body.vDate1,req.body.vDate2,req.body.vName,req.body.city];//查询条件

    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new Voice().getVoiceList(params,page,function(result){
        res.send(result);
    });
    debug('车友汇信息列表');
});


/**
 * 添加我代言信息
 */
router.post('/auth/voice/addVoice', function(req,res){
console.log(req.body.cid+'~~~~~~~~~~~');
    var coords = req.body.coords;
    var imgPathOfBus = 'images/circleimgs/voice/voice'+req.body.cid;//根据城市ID创建目录
    console.log(req.body.coords+' '+imgPathOfBus);
    if(!fs.existsSync('public/'+imgPathOfBus)){
        fs.mkdirSync('public/'+imgPathOfBus);
    }
    console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
    gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
        .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
            if (!err){
                fs.unlinkSync(req.files.file.path);//删除文件原
                var img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                new Voice(req.body.title,req.body.content,req.body.total,req.body.currenttotal,new Date(req.body.starttime),
                    new Date(req.body.endtime),img,req.body.cid,new Date())
                    .save(function(result){
                        res.setHeader('Content-Type','text/html');
                        res.send(result);
                    });
            }
        });
});

/**
 * 编辑我代言信息
 */
router.post('/auth/voice/editVoice', function(req,res){
    console.log(req.body.coords);
    var img='public/'+req.body.pic;
    if(req.files.file){//判断图片需不需要更新
        var coords = req.body.coords;
        var imgPathOfBus = 'images/circleimgs/voice/voice'+req.body.cid;//根据产品ID创建目录
        if(!fs.existsSync('public/'+imgPathOfBus)){
            fs.mkdirSync('public/'+imgPathOfBus);
        }
        console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
        gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
            .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
                if (!err){

                    fs.exists(req.files.file.path, function (exists) {
                        if(exists){
                            fs.unlinkSync(req.files.file.path);//删除文件原
                        }
                    });
                    fs.exists(img, function (exists) {
                        if(exists){
                            fs.unlinkSync(img);//删除原来的图片
                        }
                    });


                    img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                    voiceUodate(req, res, img);
                }
            });
    }else{
        sdUodate(req, res, req.body.pic);
    }
});

/**
 * 删除选中
 */
router.post('/auth/voice/delVoice', function(req,res){
    var ids = req.body['ids'];
    var imgs = req.body['imgs'];
    console.log(imgs+'11111111111111111111111');
    new Voice().delVoice(ids,function(result){
        imgs = imgs.split(',');
        for(var i=0;i<imgs.length;i++){
            fs.unlinkSync('public/'+imgs[i]);//删除原来的图片
        }

        res.send(result);
    });
});


/**
 * 更新信息
 * @param req
 * @param res
 * @param img
 */
function voiceUodate(req, res, img){
    var voice = new Voice(req.body.title,req.body.content,req.body.total,req.body.currenttotal,new Date(req.body.starttime),
        new Date(req.body.endtime),img,req.body.cid,new Date(req.body.createtime));
    voice.id = req.body.id;
    voice.update(function(result){
        res.setHeader('Content-Type','text/html');
        res.send(result);
    });
}


/**
 * 我代言活动列表
 */
router.post('/act/actList',function(req,res){
    var params = [req.body.actDate1,req.body.actDate2,req.body.actName];//查询条件

    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new Activity().getActivityList(params,page,function(result){
        res.send(result);
    });
    debug('车友汇信息列表');
});


/**
 * 添加我代言信息
 */
router.post('/auth/act/addActivity', function(req,res){
    console.log(req.body.cid+'~~~~~~~~~~~');
    var coords = req.body.coords;
    var imgPathOfBus = 'images/circleimgs/activity/activity'+req.body.cid;//根据城市ID创建目录
    console.log(req.body.coords+' '+imgPathOfBus);
    if(!fs.existsSync('public/'+imgPathOfBus)){
        fs.mkdirSync('public/'+imgPathOfBus);
    }
    console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
    gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
        .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
            if (!err){
                fs.unlinkSync(req.files.file.path);//删除文件原
                var img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                new Activity(req.body.title,req.body.content,req.body.total,req.body.currenttotal,new Date(req.body.starttime),
                    new Date(req.body.endtime),img,req.body.cid,new Date())
                    .save(function(result){
                        res.setHeader('Content-Type','text/html');
                        res.send(result);
                    });
            }
        });
});

/**
 * 编辑我代言信息
 */
router.post('/auth/act/editActivity', function(req,res){
    console.log(req.body.coords);
    var img='public/'+req.body.pic;
    if(req.files.file){//判断图片需不需要更新
        var coords = req.body.coords;
        var imgPathOfBus = 'images/circleimgs/activity/activity'+req.body.cid;//根据产品ID创建目录
        if(!fs.existsSync('public/'+imgPathOfBus)){
            fs.mkdirSync('public/'+imgPathOfBus);
        }
        console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
        gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
            .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
                if (!err){
                    fs.unlinkSync(req.files.file.path);//删除文件原
                    fs.unlinkSync(img);//删除原来的图片
                    img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                    actUpdate(req, res, img);
                }
            });
    }else{
        sdUodate(req, res, req.body.pic);
    }
});

/**
 * 删除选中
 */
router.post('/auth/act/delActivity', function(req,res){
    var ids = req.body['ids'];
    console.log(ids);
    var imgs = req.body['imgs'];
    new Activity().delVoice(ids,function(result){
        imgs = imgs.split(',');
        for(var i=0;i<imgs.length;i++){
            fs.unlinkSync('public/'+imgs[i]);//删除原来的图片
        }
        res.send(result);
    });
});


/**
 * 更新信息
 * @param req
 * @param res
 * @param img
 */
function actUpdate(req, res, img){
    var activity = new Activity(req.body.title,req.body.content,req.body.total,req.body.currenttotal,new Date(req.body.starttime),
        new Date(req.body.endtime),img,req.body.cid,new Date(req.body.createtime));
    activity.id = req.body.id;
    activity.update(function(result){
        res.setHeader('Content-Type','text/html');
        res.send(result);
    });
}


/*用户报名活动*/
router.post('/signActivity', function(req, res, next){
    new UserModel().signActivity(req.body, function(result){
        sendResult(res, result);
    })
})
router.post('/checkActivity', function(req, res, next){
    debug('checkActivity-' + req.body.uid +'-'+req.body.aname+'-'+req.body.aid);
    new UserModel().checkActivity(req.body, function(result){
        res.send(''+ result);
    })
})
router.post('/comment/list', function(req, res, next){
    new UserModel().listComment(req.body, function(data){
        debug(data[0]);
        sendResult(res, data);
    })
})

var sendResult = function(res, result){
    res.setHeader('Content-Type','text/html');
    res.send(result);
}

/**
 * 获取图片轮播路径
 */
router.get('/appidx/getIdxFiles', function(req, res){
    //var imgs = [];
    fs.readdir('public/images/idx', function(err,files){
        for(var i=0;i<files.length;i++){
            files[i] = '/images/idx/'+files[i];
        }
        console.log(files+'-------');
        res.send(files);
    });

});
/**
 * 图片轮播文件上传
 */
router.post('/auth/appidx/editAppIdx', function(req, res){
    var img = req.body.oldidx;//更新之前的图片路径
    res.setHeader('Content-Type','text/html');
    if(req.files.file){//判断图片需不需要更新
        var coords = req.body.coords;
        var imgPath = '/images/idx/'+req.files.file.name;
        gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
            .resize(600, 600)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write('public'+imgPath, function (err) {
                if (!err){
                    fs.unlinkSync(req.files.file.path);//删除upload下的文件
                    if(img&&img!=''){
                        console.log('删除'+img);
                        fs.unlinkSync('public'+img);//删除原来的图片
                    }
                    res.send(imgPath);
                }else{
                    res.send(false);
                }
            });
    }else{
        res.send(imgPath);
    }

});

module.exports = router;
